package com.product.shiro;

import com.alibaba.fastjson.JSONObject;
import com.product.mould.Mould;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.authc.AuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Slf4j
public class ClientShiroThree extends AuthenticationFilter {
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse response1) throws Exception {
        HttpServletResponse response = (HttpServletResponse) response1;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String ajax = request.getHeader("x-requested-with");

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        if (null==ajax) {
            log.info("=====不是ajax");
//            response.sendRedirect("/login");
            PrintWriter writer = response.getWriter();
            writer.write(JSONObject.toJSONString(new Mould<String>().setData(401, "token异常")));
        }else {
            log.info("=====是ajax"+ajax);
            response.getWriter().write("访问异常");
        }
        return false;
    }
    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse response, Object mappedValue) {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String token = request.getHeader(TokenUtil.Authorization);
        log.info("账户token："+token);
        if (null == token||"".equals(token)) {
            log.info("token为空");
            return false;
        }
        //验证token的真实性
        try {
            TokenUtil.getTokenBody(token);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("token有问题");
            return false;
        }
        return true;
    }
}